global !p

from mdtex.scopes import math

roman_list = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}
interval   = '\\kern{-0.1em}'

def int_to_roman(num):
    if num > 1666:
        return
    def roman_num(num):
        for r in roman_list.keys():
            x, y = divmod(num, r)
            yield roman_list[r] * x
            num -= r * x
            if num <= 0:
                break
    return interval.join([b for a in roman_num(num) for b in a])

endglobal

context "math()"
snippet "\b(\d{1,4})rmn" "罗马数字 Roman Number" r
`!p snip.rv = '\\mathrm{' + result + '}' if (result := int_to_roman(int(match.group(1)))) else match.group(1)`
endsnippet
